package com.shanpin.shebao.admin.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shanpin.core.utils.DateUtil;
import com.shanpin.shebao.admin.excel.BuyExcelDto;
import com.shanpin.shebao.admin.excel.ExcelService;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.shanpin.core.http.MJsonView;
import com.shanpin.shebao.admin.ListQueryBuilder;
import com.shanpin.shebao.admin.module.channel.ChannelService;
import com.shanpin.shebao.admin.module.city.CityCacheService;
import com.shanpin.shebao.admin.module.shebao.SBConfigService;
import com.shanpin.shebao.basedb.model.CityConfig;
import com.shanpin.shebao.common.URI;
import com.shanpin.shebao.form.BuyQueryForm;
import com.shanpin.shebao.model.BuyDetail;
import com.shanpin.shebao.service.BuyService;
import com.shanpin.shebao.utility.Criterition;
import com.shanpin.shebao.utility.MoreCriteria;
import com.shanpin.shebao.utility.PageModel;

/**
 * 买单管理控制器
 * @author 品讯科技
 *
 */
@Controller
public class BuyAdminController extends ResourceController {
	
	/**
	 * 图片服务器前缀
	 */
	@Value("${IMAGE_SERVICE}")
	private String IMAGE_SERVICE;
	
	@Autowired
	private BuyService buyService;
	@Autowired
	private SBConfigService sbConfigService;
	@Autowired
	private ChannelService channelService;
	@Autowired
	private CityCacheService cityCacheService;
	@Autowired
	private ExcelService excelService;
	

	/**
	 * 买单管理查询列表页面
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 */
	@RequestMapping(value=URI.BUY_LIST, method=RequestMethod.GET)
	public ModelAndView queryPageBy(HttpServletRequest request, HttpServletResponse response, 
			BuyQueryForm form) {
		if(StringUtil.isNotBlank(form.getCity_code())) {
			int cid = sbConfigService.getMainConfig(Integer.parseInt(form.getCity_code().trim()));
			form.setCid(cid);
		}
		form.setIs_kefu(false);
		MoreCriteria<String, Criterition> mc = ListQueryBuilder.buyListQuery(form);
		
		int pageSize = PAGE_SIZE;
		//导数据需要,暂时分页改成可以通过参数传过来
		String pageSizeStr = request.getParameter("pageSize");
		if(StringUtil.isNotBlank(pageSizeStr)) {
			pageSize = Integer.parseInt(pageSizeStr);
			if(pageSize > 500) {
				pageSize = 500;
			}
		}
		int page = parsePageNo(form.getPageNo());
		
		PageModel pageModel = buyService.queryPage(page, pageSize, mc);
		
		ModelAndView mav = new ModelAndView("order/buy_manage");
		mav.addObject("pageModel", pageModel);
		mav.addObject("buyQueryForm", form);
		
		mav.addObject("cityList", cityCacheService.listAllCity());
		mav.addObject("payChannels", channelService.listPayChannel());
		
		//查询有买单的城市
		queryExistedCities(mav);
		mav.addObject("list_uri", URI.SBA + URI.BUY_LIST);
		mav.addObject("audit_uri", URI.SBA + URI.BUY_EDIT_AUDIT);
		mav.addObject("view_idcard_uri", URI.SBA + URI.USER_SHEBAO_VIEW_IDCARD);
		mav.addObject("export_uri", URI.SBA + URI.BUY_NOT_AUDIT_EXPORT);

		return mav;
	}
	
	private void queryExistedCities(ModelAndView mav) {
		List<Integer> existedCities = buyService.queryExistedCities();
		
		List<CityConfig> existedCityList = new ArrayList<>();
		TreeSet<CityConfig> pCitySet = cityCacheService.cityCode2Exist(existedCities, existedCityList);
		mav.addObject("existedCityList", existedCityList);
		mav.addObject("pCitySet", pCitySet);
	}
	
	
	/**
	 * 更改审核状态
	 * @param request
	 * @param response
	 * @param
	 * @return
	 */
	@RequestMapping(value=URI.BUY_EDIT_AUDIT, method=RequestMethod.GET)
	public Object updateAudit(HttpServletRequest request, HttpServletResponse response, 
			String buy_noV, int auditV, String reason) {
		if(StringUtils.isNotBlank(buy_noV)) {
			BuyDetail buyDetail = buyService.queryBy(buy_noV);
			if(buyDetail == null) {
				return MJsonView.ok(buy_noV + " 买单不存在。");
			}
			buyDetail.setAudit(auditV);
			boolean r = buyService.updateAudit(buyDetail, reason);
			if (r) {
				return MJsonView.ok((StringUtils.isBlank(buyDetail.getUser_name()) ? buyDetail.getPay_user() : buyDetail.getUser_name())
						+ (auditV==0 ? " 取消了审核。" : " 审核了(生成了短信通知)。"));
			}
			return MJsonView.fail(buy_noV + " 订单审核时出现了问题。");
		}
		return MJsonView.fail("买单号是空的。");
	}

	/**
	 * 未审核的未支付的买单数据导出
	 */
	@RequestMapping(value = URI.BUY_NOT_AUDIT_EXPORT)
	public void exportNotAuditList( HttpServletResponse response, BuyQueryForm form) throws Exception {
		form.setIs_kefu(false);
		MoreCriteria<String, Criterition> mc = ListQueryBuilder.buyListQuery(form);
		PageModel pageModel = buyService.queryExportBuyPage(1, 15000, mc);
		List<BuyDetail> buyList = pageModel.getRecordList();
		List<BuyExcelDto> dtoList = buyService.buildBuyAuditExportDto(buyList);
		String[] headers = { "购买城市", "户籍性质", "购买月份",
				"购买月数","是否新办卡",
				"类型", "参保人", "手机",
				"是否补缴","购买时间","总金额",
				"社保","社保服务费","公积金",
				"公积金服务费", "办卡费",
				"买单号","支付号"};
		String[] fields = { "city", "hukou", "start_month",
				"month_num","new_card",
				"pay_for", "user_name","pay_user",
				"added", "gen_time", "total_fee",
				"shebaos", "shebao_charge", "funds",
				"fund_charge", "card_charge",
				"buy_no","trade_no"};
		String fileName = "buy_not_audit_"+ DateUtil.currentStr("M-dd_HH:mm")+".xls";
		excelService.exportExcel(fileName,"买单表",headers,fields,dtoList,response);
	}
}
